﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Timers;
using Leadtools.Codecs;
using SmallERP.Bll.PinBan;
using SmallERP.MODEL.FenPian;
using SmallERP.MODEL.FoundationModel;
using SmallERP.PinBan.ImportPhoto.View;
using Timer = System.Timers.Timer;
using System.Windows.Forms;
using System.Drawing;
using Smallerp.Contracts.DataContracts;
using System.ServiceModel;
using Smallerp.Contracts;
using System.ComponentModel;
using Lucene.Net.Analysis;
using SmallERP.COM;
using SmallERP.PinBan.PB.Presenter;


namespace SmallERP.PinBan.ImportPhoto.Presenter
{
    public class ImportPhotoPresenter
    {
        private IFrmImportPhoto _view;
        private ImportPhotoBLL _bll;
        public ImportPhotoPresenter(IFrmImportPhoto iview)
        {
            //RasterCodecs.Startup();
            _view = iview;
            InitData();
            RasterCodecs.Startup();
        }
        #region API
        //API
        /// <summary>
        /// 移动文件，文件夹
        /// </summary>
        /// <param name="src"></param>
        /// <param name="dst"></param>
        /// <param name="flag">1如果文件存在，则替换；2如移动到不同的卷，则复制文件并删除原来的文件；3移动操作在系统重启后才真正执行</param>
        /// <returns></returns>
        [DllImport("kernel32", EntryPoint = "MoveFileEx", CharSet = CharSet.Unicode)]
        public static extern bool MoveFile(string src, string dst, long flag);

        /// <summary>
        /// 创建文件夹
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        [DllImport("kernel32", EntryPoint = "CreateDirectory")]
        public static extern bool CreateDirectory(string path);

        /// <summary>
        /// 移除文件夹
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        [DllImport("kernel32", EntryPoint = "RemoveDirectory")]
        public static extern bool RemoveDirectory(string path);

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        [DllImport("kernel32", EntryPoint = "DeleteFile")]
        public static extern bool DelFile(string path);

        /// <summary>
        /// 打开文件夹
        /// </summary>
        /// <param name="hwnd"></param>
        /// <param name="lpszOp"></param>
        /// <param name="lpszFile"></param>
        /// <param name="lpszParams"></param>
        /// <param name="lpszDir"></param>
        /// <param name="FsShowCmd"></param>
        /// <returns></returns>
        [DllImport("shell32.dll", EntryPoint = "ShellExecute")]
        public static extern int OpenFolder(IntPtr hwnd, StringBuilder lpszOp, StringBuilder lpszFile, StringBuilder lpszParams, StringBuilder lpszDir, int FsShowCmd);
        #endregion
        ~ImportPhotoPresenter()
        {
            RasterCodecs.Shutdown();
        }
        private string strYiTiaoSe = string.Empty;
        private string strPinban = string.Empty;
        Timer timeMove = new Timer();
        private double PlusValues = 0;
        void InitData()
        {

            _view._proxyOperateDB = new ChannelFactory<IOperateDB>("IOperateDB");
            _view._OperateDb = _view._proxyOperateDB.CreateChannel();

            _bll = new ImportPhotoBLL(_view._OperateDb);
            _bll.Tel += new ImportPhotoBLL.TellView(_bll_Tel);
            _bll.TelOrderID += new ImportPhotoBLL.TellView1(_bll_TelOrderID);
            _bll.TelCurrName += new ImportPhotoBLL.TellView1(_bll_TelCurrName);
            _view.OrderViewList = new List<OrderViewDCT>();
            _bll.ProgressEvent += new ImportPhotoBLL.ProgressDelegate(_bll_ProgressEvent);
            _bll.TelViewPhotoInfo += new ImportPhotoBLL.TellView1(_bll_TelViewPhotoInfo);
            _view.PrintBind = _view._OperateDb.GetAllPrinters();
            //   _view.PrintBind.Add(new PrinterDCT() { PrinterID = 0, PName = "无" });

            _view.FaceBind = _view._OperateDb.GetAllPaperFace();
            // _view.FaceBind.Add(new PaperFaceDCT() { PaperFaceId = 0, PaperFaceName = "无" });
            _view.TypeBind = _view._OperateDb.GetAllPaperType();
            //  _view.TypeBind.Add(new PaperTypeDCT() { PaperTypeId = 0, PaperTypeName = "无" });
            _view.BingPaperFace();
            _view.BingPaperType();
            _view.BingPrint();
            _view.OrderPath = _bll.GetOrderRootDir();
            ImportDataTransfer.FileSavePath = _bll.GetSaveFilePath();
            strYiTiaoSe = _view.OrderPath + "\\已调色";
            strPinban = _view.OrderPath + "\\拼版";

            _view.OrderViewList = _bll.GetUnMoveView();
            _view.RushViewData(_view.OrderViewList);
            _view.CurrTaskPath = new List<string>();
            // _view.RefreshDataCreateView();
            timeMove.Interval = 5000;

            timeMove.Elapsed += new ElapsedEventHandler(timeMove_Elapsed);
            timeMove.Start();
            bgwAnlseFile.WorkerSupportsCancellation = true;
            bgwAnlseFile.WorkerReportsProgress = true;
            bgwAnlseFile.DoWork += new DoWorkEventHandler(bgwAnlseFile_DoWork);
            bgwAnlseFile.ProgressChanged += new ProgressChangedEventHandler(bgwAnlseFile_ProgressChanged);
            bgwAnlseFile.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgwAnlseFile_RunWorkerCompleted);
        }

        string _bll_TelViewPhotoInfo(string str)
        {
            AddMessage addmsg = new AddMessage(_view.ShowReadFileName);
            addmsg(str);
            return "";
        }

        void _bll_ProgressEvent(int p)
        {
            _view.SetProcessValue(p, 100);
        }

        void bgwAnlseFile_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            //throw new NotImplementedException();
            List<PhotoDCT> photolist = new List<PhotoDCT>();
            foreach (var item in _view.OrderViewList)
            {
                foreach (var photo in item.PhotoS)
                {
                    if (photo.Status == (int)SmallERP.COM.Status.PhotoStatus.DpiErr)
                    {
                        photolist.Add(photo);
                    }
                }
            }
            if (photolist.Count > 0)//如果存在错误照片
            {
                _view.ShowErrorPhotoList(photolist);
            }
        }

        void bgwAnlseFile_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            //throw new NotImplementedException();
        }

        void bgwAnlseFile_DoWork(object sender, DoWorkEventArgs e)
        {
            List<string> pathList = (List<string>)e.Argument;
            if (ImportDataTransfer.FileSavePath == "0")
            {
                CreateForMuli(e.Argument);
            }
            else
            {
                CreateForMuliPreMoveFile(e.Argument);
            }
        }

        string _bll_TelCurrName(string str)
        {
            OrderViewDCT Currview = _view.OrderViewList.FirstOrDefault(p => str.IndexOf(p.OrderName) > -1);
            if (Currview != null)
            {
                Currview.MoveStatus = "正在移动";
            }
            //_view.OrderViewList.Remove(delview);
            _view.RefreshDataCreateView();
            _view.RushViewData(_view.OrderViewList);
            return "";
        }

        string _bll_TelOrderID(string str)
        {
            //int orderID = Convert.ToInt32(str);
            OrderViewDCT delview = _view.OrderViewList.FirstOrDefault(p => str.IndexOf(p.OrderName) > -1);
            _view.OrderViewList.Remove(delview);
            _view.RefreshDataCreateView();
            _view.RushViewData(_view.OrderViewList);
            // _view.OrderViewList.OrderBy(p=>p.Remark,)
            return "";
        }

        string _bll_Tel(string str, Color color)
        {
            try
            {

                _view.ShowImportMessage(DateTime.Now + str + Environment.NewLine, color);
            }
            catch
            { }
            return str;
        }

        private bool bStopMove = false;

        void timeMove_Elapsed(object sender, ElapsedEventArgs e)
        {
            if (!bStopMove)
            {
                //int intRtn = _bll.MoveDirPhoto();
                timeMove.Enabled = false;
                try
                {
                    int intRtn = _bll.MoveDirPhoto();
                    if (intRtn != 0)
                    {
                        bStopMove = false;

                    }
                    else
                    {
                        bStopMove = true;
                        _view.ThawyFrm();
                    }

                    if (_bll.GetUnMoveView().Count == 0)
                    {
                        bStopMove = true;
                        _view.ThawyFrm();
                    }

                }
                catch (Exception ex)
                {
                    _view.ShowImportMessage(DateTime.Now + ex.Message + Environment.NewLine, Color.Black);

                }
                finally
                {
                    timeMove.Enabled = true;
                }
            }
        }

        public bool isStop = false;
        /// <summary>
        /// 递归找到文件夹下所有照片文件
        /// </summary>
        /// <param name="inPath"></param>
        /// <param name="inList"></param>
        public void GetAllPicByDir(string inPath, List<string> inList)
        {
            if (isStop)
            {
                return;
            }
            string picTag = ".JPEG.JPG.TIF.BMP.TIFF.TIF";
            DirectoryInfo rootDir = new DirectoryInfo(inPath);
            if (rootDir.Exists)
            {
                FileInfo[] fileList = rootDir.GetFiles();
                foreach (FileInfo info in fileList)
                {
                    if (isStop)
                    {
                        return;
                    }
                    if (picTag.Contains(info.Extension.ToUpper()))
                    {
                        inList.Add(info.FullName);
                    }
                    else
                    {
                        if (info.FullName.ToUpper().IndexOf(("Thumbs.db").ToUpper()) == -1 && !info.FullName.ToUpper().EndsWith("TXT"))
                        {
                            _view.ShowImportMessage(DateTime.Now + " 导片时发现不能处理的文件：" + info.FullName + Environment.NewLine, Color.Red);
                        }
                    }
                }
                DirectoryInfo[] listDir = rootDir.GetDirectories();
                foreach (DirectoryInfo dir in listDir)
                {
                    GetAllPicByDir(dir.FullName, inList);
                }
            }

        }
        delegate void AddMessage(string msg);
        delegate void ChangeProcess(int curr, int Count);

        private delegate void RichShow(string msg);
        public int CurrTask;//当前正在分析的目录数量
        //ImageDPI.ClassDPIClass DPIClass = new ImageDPI.ClassDPIClass();
        // List<string> CurrTaskPath = new List<string>();//当前正在分析的目录防止重复拖
        private Thread threadCreate;
        public void CreateForMuli(object obj)
        {
            _view.IsAnalyIng = true;
            _view.SetOperatSatus();
            List<string> inListTagartDir = (List<string>)obj;
            AddMessage addMessage = new AddMessage(_view.ShowReadFileName);
            ChangeProcess changeProcess = new ChangeProcess(_view.SetProcessValue);
            RasterCodecs codecs = null;
            try
            {
                codecs = new RasterCodecs();
            }
            catch
            {
                RasterCodecs.Startup();
                codecs = new RasterCodecs();
            }
            CurrTask += inListTagartDir.Count;
            foreach (string inTagartDir in inListTagartDir)
            {
                bool isRepeat = false;
                if (!_view.CurrTaskPath.Contains(inTagartDir))
                {
                    _view.CurrTaskPath.Add(inTagartDir);
                }
                else
                {
                    _view.ShowImportMessage(DateTime.Now + " 文件夹已存在于列表中：" + inTagartDir + Environment.NewLine, Color.Red);
                    CurrTask--;
                    continue;
                    //isRepeat=true;

                }
                addMessage("当前分析目录：" + inTagartDir);

                try
                {


                    OrderViewDCT order = new OrderViewDCT();
                    order.AllFace = _view.FaceBind;
                    order.AllPrint = _view.PrintBind;
                    order.AllType = _view.TypeBind;

                    order.OrderName = inTagartDir.Substring(inTagartDir.LastIndexOf("\\") + 1);

                    string[] arrStr = inTagartDir.Split('\\');
                    int myCount = arrStr.Count();
                    if (myCount >= 3)
                    {
                        order.FatherFolder = arrStr[arrStr.Count() - 2];
                        order.GranddadFolder = arrStr[arrStr.Count() - 3];
                    }
                    else if (myCount >= 2)
                    {
                        order.FatherFolder = arrStr[arrStr.Count() - 2];
                        order.GranddadFolder = order.FatherFolder;
                    }
                    else
                    {
                        order.FatherFolder = order.OrderName;
                        order.GranddadFolder = order.OrderName;
                    }

                    order.OrilOrderPath = inTagartDir;
                    order.OrderPath = inTagartDir;
                    order.Priority = _view.IntPriority;
                    order.ProductNum = 1;
                    order.PaperTypeInfo = _view.PaperTypeInfo;
                    order.PaperFace = _view.PaperFaceInfo;
                    order.PrintInfo = _view.PrinterInfo;

                    order.Status = (int)COM.Status.OrderStatus.Doing;

                    order.Remark = "";
                    List<PhotoDCT> photoList = new List<PhotoDCT>();
                    List<string> fileList = new List<string>();
                    //if (_bll.CheckOrder(order))
                    if (CheckOrderRe(order))
                    {
                        _view.ShowImportMessage(DateTime.Now + " 文件夹重复导入" + order.OrderName + Environment.NewLine, Color.Red);

                    }

                    GetAllPicByDir(inTagartDir, fileList);///取到所有的文件

                    if (isStop)
                    {
                        return;
                    }
                    ///
                    PhotoDCT photo;
                    int currPoint = 0;
                    //_view.ShowReadFileName(inTagartDir);
                    //addMessage(inTagartDir);
                    if (fileList.Count == 0)
                    {
                        _view.CurrTaskPath.Remove(inTagartDir);
                        _view.ShowImportMessage(DateTime.Now + " 发现空文件目录:" + inTagartDir + Environment.NewLine, Color.Black);

                        continue;
                    }
                    foreach (string s in fileList)
                    {
                        photo = new PhotoDCT();
                        CodecsImageInfo img = null;
                        try
                        {
                            img = codecs.GetInformation(s, true);
                        }
                        catch (Exception)
                        {
                            _view.ShowImportMessage(DateTime.Now + " 发现损坏文件：" + s + Environment.NewLine, Color.Red);

                            continue;

                        }
                        string PhotoName = s.Substring(inTagartDir.Length);
                        int photoXDPI = img.XResolution;
                        int photoYDPI = img.YResolution;


                        if (img.ColorSpace == CodecsColorSpaceType.Cmyk)
                        {
                            if (DataTransfer.CurPrinerInfo.PrinterType == 1)
                            {
                                photo.ColorType = 1;
                            }
                            else
                            {
                                photo.Status = (int)SmallERP.COM.Status.PhotoStatus.ColorTypeError;
                                MessageBox.Show("发现 " + s + " 文件格式为Cmyk，不能在" + DataTransfer.CurPrinerInfo.PName + " 上打印！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                                //photoXDPI = -1;
                            }

                        }
                        else
                        {
                            if (DataTransfer.CurPrinerInfo.PrinterType == 0)
                            {
                                photo.ColorType = 0;
                            }
                            else
                            {
                                photo.Status = (int)SmallERP.COM.Status.PhotoStatus.ColorTypeError;
                                MessageBox.Show("发现 " + s + " 文件格式为RGB，不能在" + DataTransfer.CurPrinerInfo.PName + " 上打印！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                            }
                        }
                        //photo.Height = (float)img.Height / photoYDPI;
                        //photo.Width = (float)img.Width / photoXDPI;
                        if (img.IsRotated)
                        {
                            photo.Height = (float)img.Width / photoYDPI;
                            photo.Width = (float)img.Height / photoXDPI;
                            photo.PixHeight = img.Width;
                            photo.PixWidth = img.Height;
                        }
                        else
                        {
                            photo.Height = (float)img.Height / photoYDPI;
                            photo.Width = (float)img.Width / photoXDPI;
                            photo.PixHeight = img.Height;
                            photo.PixWidth = img.Width;
                        }
                        //photo.Height = Math.Round(photo.Height, 1);
                        //photo.Width = Math.Round(photo.Width, 1);
                        //photo.Height = Math.Round(photo.Height + PlusValues, 1);
                        //photo.Width = Math.Round(photo.Width + PlusValues, 1);
                        if (photo.Height > photo.Width)
                        {
                            photo.SizeCM = string.Format("{0:0.##}", photo.Height * 2.54) + "X" +
                                               string.Format("{0:0.##}", photo.Width * 2.54);
                            photo.SizeInch = string.Format("{0:0.##}", photo.Height) + "X" +
                                                 string.Format("{0:0.##}", photo.Width);
                        }
                        else
                        {
                            photo.SizeCM = string.Format("{0:0.##}", photo.Width * 2.54) + "X" +
                                           string.Format("{0:0.##}", photo.Height * 2.54);
                            photo.SizeInch = string.Format("{0:0.##}", photo.Width) + "X" +
                                             string.Format("{0:0.##}", photo.Height);
                        }
                        photo.PhotoName = s.Substring(inTagartDir.Length);
                        photo.TotalNum = SetPhotoNum(s);
                        photo.PicOripath = s;
                        photo.PicPath = s;
                        //photo.PixHeight = Convert.ToInt32(photo.Height * photoXDPI);
                        //photo.PixWidth = Convert.ToInt32(photo.Width * photoXDPI);
                        //photo.PixHeight = img.Height + Convert.ToInt32(PlusValues * photoXDPI);
                        //photo.PixWidth = img.Width + Convert.ToInt32(PlusValues * photoXDPI);

                        photo.PaperFaceId = order.PaperFace.PaperFaceId;
                        photo.PaperFace = order.PaperFace.PaperFaceName;
                        photo.PaperTypeID = order.PaperTypeInfo.PaperTypeId;
                        photo.PaperType = order.PaperTypeInfo.PaperTypeName;

                        photo.PicPath = s;//剪切的目的文件
                        photo.PicOripath = s;
                        photo.DPI = photoXDPI;


                        //if (IniFile.IsAutoAnlyseDXF)
                        //{
                        //    string conFile = OrderDxfItem(ImportDataTransfer.DxfList, s).FirstOrDefault();
                        //    if (conFile != null)
                        //    {
                        //        photo.DXFContent = DxfExtend.GetFileContent(conFile);
                        //        photo.DXFFilePath = conFile;
                        //    }
                        //}
                        photoList.Add(photo);

                        changeProcess(currPoint, fileList.Count);
                        currPoint++;

                    }

                    order.PhotoS = photoList;
                    _view.OrderViewList.Add(order);
                    _view.RefreshDataCreateView();
                    changeProcess(100, 100);
                }
                catch (Exception)
                {

                    throw;
                }

                CurrTask--;
                _view.CurrTaskPath.Remove(inTagartDir);
                addMessage("当前分析目录：" + _view.OrderPath);
                _view.IsAnalyIng = false;
                _view.SetOperatSatus();
            }
            //RasterCodecs.Shutdown();
            _view.IsAnalyIng = false;
            _view.SetOperatSatus();
        }
        private List<string> OrderDxfItem(List<string> inDirList, string inStandStr)
        {
            List<string> rl = new List<string>();
            Dictionary<string, int> resultDict = new Dictionary<string, int>();
            List<string> standList = AnalyserStr(inStandStr);
            foreach (string dirStr in inDirList)
            {
                List<string> dirList = AnalyserStr(dirStr);
                var r = dirList.Intersect(standList);
                resultDict.Add(dirStr, r.Count());
            }
            var rd = resultDict.OrderByDescending(or => or.Value);
            foreach (KeyValuePair<string, int> keyValuePair in rd)
            {
                rl.Add(keyValuePair.Key);
            }
            return rl;
        }

        private List<string> AnalyserStr(string instr)
        {
            List<string> rtList = new List<string>();
            Analyzer analyzer = new Lucene.China.ChineseAnalyzer();
            StringReader sr = new StringReader(instr);
            TokenStream stream = analyzer.TokenStream(null, sr);

            Token t = stream.Next();
            while (t != null)
            {
                string t1 = "";

                t1 = t.ToString(); //显示格式： (字符,0,2) ，需要处理 
                t1 = t1.Replace("(", "");
                char[] separator = { ',' };
                var tep = t1.Split(separator);
                if (tep.Count() > 0)
                {
                    rtList.Add(tep[0]);
                }
                t = stream.Next();



            }
            return rtList;

        }
        public void CreateForMuliPreMoveFile(object obj)
        {
            string targetFolder = ImportDataTransfer.FileSavePath;
            _view.IsAnalyIng = true;
            _view.SetOperatSatus();
            List<string> inListTagartDir = (List<string>)obj;
            AddMessage addMessage = new AddMessage(_view.ShowReadFileName);
            ChangeProcess changeProcess = new ChangeProcess(_view.SetProcessValue);
            RasterCodecs codecs = null;
            try
            {
                codecs = new RasterCodecs();
            }
            catch
            {
                RasterCodecs.Startup();
                codecs = new RasterCodecs();
            }
            CurrTask += inListTagartDir.Count;
            foreach (string inTagartDir in inListTagartDir)
            {
                bool isRepeat = false;
                if (!_view.CurrTaskPath.Contains(inTagartDir))
                {
                    _view.CurrTaskPath.Add(inTagartDir);
                }
                else
                {
                    _view.ShowImportMessage(DateTime.Now + " 文件夹已存在于列表中：" + inTagartDir + Environment.NewLine, Color.Red);
                    CurrTask--;
                    continue;
                    //isRepeat=true;

                }
                addMessage("当前分析目录：" + inTagartDir);

                try
                {


                    OrderViewDCT order = new OrderViewDCT();
                    order.AllFace = _view.FaceBind;
                    order.AllPrint = _view.PrintBind;
                    order.AllType = _view.TypeBind;

                    order.OrderName = inTagartDir.Substring(inTagartDir.LastIndexOf("\\") + 1);

                    string[] arrStr = inTagartDir.Split('\\');
                    int myCount = arrStr.Count();
                    if (myCount >= 3)
                    {
                        order.FatherFolder = arrStr[arrStr.Count() - 2];
                        order.GranddadFolder = arrStr[arrStr.Count() - 3];
                    }
                    else if (myCount >= 2)
                    {
                        order.FatherFolder = arrStr[arrStr.Count() - 2];
                        order.GranddadFolder = order.FatherFolder;
                    }
                    else
                    {
                        order.FatherFolder = order.OrderName;
                        order.GranddadFolder = order.OrderName;
                    }

                    order.OrilOrderPath = inTagartDir;
                    order.OrderPath = targetFolder + "\\" + order.OrderName;
                    order.Priority = _view.IntPriority;
                    order.ProductNum = 1;
                    order.PaperTypeInfo = _view.PaperTypeInfo;
                    order.PaperFace = _view.PaperFaceInfo;
                    order.PrintInfo = _view.PrinterInfo;

                    order.Status = (int)COM.Status.OrderStatus.WaitMove;

                    order.Remark = "";
                    List<PhotoDCT> photoList = new List<PhotoDCT>();
                    List<string> fileList = new List<string>();
                    //if (_bll.CheckOrder(order))
                    if (CheckOrderRe(order))
                    {
                        _view.ShowImportMessage(DateTime.Now + " 文件夹重复导入" + order.OrderName + Environment.NewLine, Color.Red);

                    }

                    GetAllPicByDir(inTagartDir, fileList);///取到所有的文件

                    if (isStop)
                    {
                        return;
                    }
                    ///
                    PhotoDCT photo;
                    int currPoint = 0;
                    //_view.ShowReadFileName(inTagartDir);
                    //addMessage(inTagartDir);
                    if (fileList.Count == 0)
                    {
                        _view.CurrTaskPath.Remove(inTagartDir);
                        _view.ShowImportMessage(DateTime.Now + " 发现空文件目录:" + inTagartDir + Environment.NewLine, Color.Black);

                        continue;
                    }
                    foreach (string s in fileList)
                    {
                        //string filePathWithoutFatherFolder = s.Substring(inTagartDir.Length + 1);///除去产品目录后的照片文件
                        photo = new PhotoDCT();
                        CodecsImageInfo img = null;
                        try
                        {
                            img = codecs.GetInformation(s, true);
                        }
                        catch (Exception)
                        {
                            _view.ShowImportMessage(DateTime.Now + " 发现损坏文件：" + s + Environment.NewLine, Color.Red);

                            continue;

                        }
                        string PhotoName = s.Substring(inTagartDir.Length + 1);
                        int photoXDPI = img.XResolution;
                        int photoYDPI = img.YResolution;


                        if (img.ColorSpace == CodecsColorSpaceType.Cmyk)
                        {
                            if (DataTransfer.CurPrinerInfo.PrinterType == 1)
                            {
                                photo.ColorType = 1;
                                photo.Status = (int)SmallERP.COM.Status.PhotoStatus.WaitMove;
                            }
                            else
                            {
                                photo.Status = (int)SmallERP.COM.Status.PhotoStatus.ColorTypeError;
                                MessageBox.Show("发现 " + s + " 文件格式为Cmyk，不能在" + DataTransfer.CurPrinerInfo.PName + " 上打印！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                                //photoXDPI = -1;
                            }

                        }
                        else
                        {
                            if (DataTransfer.CurPrinerInfo.PrinterType == 0)
                            {
                                photo.ColorType = 0;
                                photo.Status = (int)SmallERP.COM.Status.PhotoStatus.WaitMove;
                            }
                            else
                            {
                                photo.Status = (int)SmallERP.COM.Status.PhotoStatus.ColorTypeError;
                                MessageBox.Show("发现 " + s + " 文件格式为RGB，不能在" + DataTransfer.CurPrinerInfo.PName + " 上打印！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                            }
                        }

                        if (img.IsRotated)
                        {
                            photo.Height = (float)img.Width / photoYDPI;
                            photo.Width = (float)img.Height / photoXDPI;
                            photo.PixHeight = img.Width;
                            photo.PixWidth = img.Height;
                        }
                        else
                        {
                            photo.Height = (float)img.Height / photoYDPI;
                            photo.Width = (float)img.Width / photoXDPI;
                            photo.PixHeight = img.Height;
                            photo.PixWidth = img.Width;
                        }

                        if (photo.Height > photo.Width)
                        {
                            photo.SizeCM = string.Format("{0:0.##}", photo.Height * 2.54) + "X" +
                                               string.Format("{0:0.##}", photo.Width * 2.54);
                            photo.SizeInch = string.Format("{0:0.##}", photo.Height) + "X" +
                                                 string.Format("{0:0.##}", photo.Width);
                        }
                        else
                        {
                            photo.SizeCM = string.Format("{0:0.##}", photo.Width * 2.54) + "X" +
                                           string.Format("{0:0.##}", photo.Height * 2.54);
                            photo.SizeInch = string.Format("{0:0.##}", photo.Width) + "X" +
                                             string.Format("{0:0.##}", photo.Height);
                        }
                        photo.PhotoName = PhotoName;
                        photo.TotalNum = SetPhotoNum(s);
                        photo.PicOripath = s;
                        photo.PicPath = targetFolder + "\\" + order.OrderName + "\\" + PhotoName;///目标文件夹


                        photo.PaperFaceId = order.PaperFace.PaperFaceId;
                        photo.PaperFace = order.PaperFace.PaperFaceName;
                        photo.PaperTypeID = order.PaperTypeInfo.PaperTypeId;
                        photo.PaperType = order.PaperTypeInfo.PaperTypeName;


                        photo.DPI = photoXDPI;

                        //if (IniFile.IsAutoAnlyseDXF)
                        //{
                        //    string conFile = OrderDxfItem(ImportDataTransfer.DxfList, s).FirstOrDefault();
                        //    photo.DXFContent = DxfExtend.GetFileContent(conFile);
                        //    photo.DXFFilePath = conFile;
                        //}

                        photoList.Add(photo);
                        changeProcess(currPoint, fileList.Count);
                        currPoint++;

                    }
                    order.PhotoS = photoList;
                    _view.OrderViewList.Add(order);
                    _view.RefreshDataCreateView();
                    changeProcess(100, 100);
                }
                catch (Exception)
                {

                    throw;
                }

                CurrTask--;
                _view.CurrTaskPath.Remove(inTagartDir);
                addMessage("当前分析目录：" + _view.OrderPath);
                _view.IsAnalyIng = false;
                _view.SetOperatSatus();
            }
            //RasterCodecs.Shutdown();
            _view.IsAnalyIng = false;
            _view.SetOperatSatus();
        }
        private int SetPhotoNum(string inFullPath)
        {

            string strCopyRule = ImportDataTransfer.CopyRule;
            string strNum = "1";
            try
            {
                foreach (string rule in strCopyRule.Split(','))
                {
                    string[] ruleArray = rule.Split('0');
                    if (string.IsNullOrEmpty(ruleArray[0]))
                    {
                        string strEnd = ruleArray[1];
                        int endPosition = inFullPath.LastIndexOf(strEnd);
                        strNum = "";
                        for (int i = endPosition - 1; i >= 0; i--)
                        {
                            string istr = inFullPath.Substring(i, 1);
                            if (char.IsDigit(istr, 0))
                            {
                                strNum = istr + strNum;
                            }
                            else
                            {
                                break;
                            }
                        }
                        if (!string.IsNullOrEmpty(strNum))//符合规则
                        {
                            break;

                        }
                        else
                        {
                            continue;
                        }

                    }
                    else
                    {
                        string strHead = ruleArray[0];
                        int headPosition = inFullPath.LastIndexOf(strHead);
                        strNum = "";
                        for (int i = headPosition + 1; i < inFullPath.Length; i++)
                        {
                            string istr = inFullPath.Substring(i, 1);
                            if (char.IsDigit(istr, 0))
                            {
                                strNum = strNum + istr;
                            }
                            else
                            {
                                break;
                            }
                        }
                        if (!string.IsNullOrEmpty(strNum))//符合规则
                        {
                            break;

                        }
                        else
                        {
                            continue;
                        }
                    }
                }
            }
            catch (Exception exx)
            {

            }

            return Convert.ToInt32(string.IsNullOrEmpty(strNum) ? "1" : strNum);
        }
        string ToDBC(string input)
        {
            char[] c = input.ToCharArray();
            for (int i = 0; i < c.Length; i++)
            {
                if (c[i] == 12288)
                {
                    c[i] = (char)32;
                }
                if (c[i] > 65280 && c[i] < 65375)
                {
                    c[i] = (char)(c[i] - 65248);
                }

            }
            return new string(c);
        }
        bool CheckOrderRe(OrderViewDCT inView)
        {
            string ProperFile = inView.OrderPath + "\\Properties.ini";
            if (File.Exists(ProperFile))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        //开线程导片
        public void CreateOrderView(List<string> inListTagartDir)
        {
            //ParameterizedThreadStart pts = new ParameterizedThreadStart(CreateForMuli);
            //threadCreate = new Thread(new ParameterizedThreadStart(CreateForMuli));
            //threadCreate.Start(inListTagartDir);
            bgwAnlseFile.RunWorkerAsync(inListTagartDir);


        }
        BackgroundWorker bgwAnlseFile = new BackgroundWorker();
        public void RushSize(List<PhotoDCT> inLisPhoto, RasterCodecs codecs)
        {
            CodecsImageInfo img = null;
            foreach (PhotoDCT photo in inLisPhoto)
            {
                try
                {
                    img = codecs.GetInformation(photo.PicPath, true);
                }
                catch { }
                int photoXDPI = img.XResolution;
                int photoYDPI = img.YResolution;
                //photoXDPI = 254;//济南金色童年定制
                //photoYDPI = 254;
                //int Dpi = DPIClass.GetImageDPIX(photo.PicPath);
                //if (photoXDPI != Dpi)
                //{
                //    photo.Status = (int)SmallERP.COM.Status.PhotoStatus.DpiErr;
                //    photoXDPI = -1;
                //}
                photo.Height = (float)img.Height / photoYDPI;
                photo.Width = (float)img.Width / photoXDPI;
                //photo.Height = Math.Round(photo.Height + PlusValues, 1);
                //photo.Width = Math.Round(photo.Width + PlusValues, 1);
                if (photo.Height > photo.Width)
                {
                    photo.SizeCM = string.Format("{0:0.##}", photo.Height * 2.54) + "X" +
                                       string.Format("{0:0.##}", photo.Width * 2.54);
                    photo.SizeInch = string.Format("{0:0.##}", photo.Height) + "X" +
                                         string.Format("{0:0.##}", photo.Width);
                }
                else
                {
                    photo.SizeCM = string.Format("{0:0.##}", photo.Width * 2.54) + "X" +
                                   string.Format("{0:0.##}", photo.Height * 2.54);
                    photo.SizeInch = string.Format("{0:0.##}", photo.Width) + "X" +
                                     string.Format("{0:0.##}", photo.Height);
                }

            }


        }

        /// <summary>
        /// 添加到数据库
        /// </summary>
        public void AddToDB()
        {
            _view.FreezeFrm();
            if (_view.OrderViewList.Count < 1)
            {
                return;
            }
            //if (CurrTask == 0)
            //{
            List<Smallerp.Contracts.DataContracts.OrderViewDCT> tempList = new List<Smallerp.Contracts.DataContracts.OrderViewDCT>();
            List<Smallerp.Contracts.DataContracts.OrderViewDCT> LastList = new List<Smallerp.Contracts.DataContracts.OrderViewDCT>();
            bool isForce = PBDataTransfer.isForcePrint;
            foreach (Smallerp.Contracts.DataContracts.OrderViewDCT view in _view.OrderViewList)
            {
                if (view.PhotoS.Count(p => p.DPI == -1) > 0)
                {
                    LastList.Add(view);

                    _view.ShowImportMessage(DateTime.Now + view.OrderName + "添加失败,存在DPI不规范照片" + Environment.NewLine, Color.Black);
                    continue;
                }
                if (view.PhotoS.Count(p => p.Status == (int)SmallERP.COM.Status.PhotoStatus.ColorTypeError) > 0)
                {
                    LastList.Add(view);
                    string errorStr = DateTime.Now + view.OrderName + "添加失败,存在格式不规范文件，请查看文件格式。";
                    MessageBox.Show(errorStr, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    _view.ShowImportMessage(errorStr + Environment.NewLine, Color.Black);
                    continue;
                }

                int intAdd = 0;
                if (ImportDataTransfer.FileSavePath == "0")
                {
                    intAdd = _bll.AddOrderToDB(view, isForce);
                }
                else
                {
                    intAdd = _bll.AddOrderToDBMoveBefore(view, isForce);
                }
                if (intAdd == 1) //清空列表
                {
                    if (ImportDataTransfer.FileSavePath != "0")
                    {
                        //_view.ShowImportMessage(DateTime.Now + view.OrderName + "添加成功，等待移动图片" + Environment.NewLine,Color.Black);
                        //tempList.Add(view);

                        //OrderViewDCT delview = _view.OrderViewList.FirstOrDefault(p => p.OrderName == view.OrderName);
                        //_view.OrderViewList.Remove(delview);

                        //_view.RefreshDataCreateView();
                        //_view.RushViewData(_view.OrderViewList);
                    }
                    else
                    {
                        StringBuilder propertiesFile = new StringBuilder();
                        propertiesFile.AppendLine(DateTime.Now + "    目录：" + view.OrderPath);
                        int iCount = 0;
                        foreach (PhotoDCT ph in view.PhotoS)
                        {
                            iCount++;
                            propertiesFile.AppendLine(iCount + "    " + ph.PicPath + "  " + ph.SizeCM);
                        }
                        if (ImportDataTransfer.FileSavePath == "0")
                        {
                            WrtieTextEn(propertiesFile, view.OrderPath + "\\Properties.ini");
                        }
                        tempList.Add(view);
                        isForce = false;
                    }
                }
                else
                {
                    LastList.Add(view);
                    _view.ShowImportMessage(DateTime.Now + view.OrderName + "添加失败,数据已存在，如存在列表中请手动删除" + Environment.NewLine, Color.Black);
                }

            }
            foreach (Smallerp.Contracts.DataContracts.OrderViewDCT view in tempList)
            {
                _view.OrderViewList.Remove(view);
            }


            //while (_view.OrderViewList.Count > 0)
            //{
            //    OrderViewDCT view = _view.OrderViewList.FirstOrDefault();
            //    int intAdd = _bll.AddOrderToDB(view);
            //    if (intAdd == 1) //清空列表
            //    {
            //        //_view.ShowImportMessage(DateTime.Now + view.OrderName + "添加成功，等待移动图片" + Environment.NewLine);
            //        //tempList.Add(view);

            //        OrderViewDCT delview = _view.OrderViewList.FirstOrDefault(p => p.OrderName == view.OrderName);
            //        _view.OrderViewList.Remove(delview);
            //        _view.RefreshDataCreateView();
            //        _view.RushViewData(_view.OrderViewList);

            //    }
            //    else
            //    {
            //        _view.ShowImportMessage(DateTime.Now + view.OrderName + "添加失败,服务器繁忙稍候操作" + Environment.NewLine, Color.Black);
            //        break;
            //    }
            //}
            // _view.ThawyFrm();
            if (ImportDataTransfer.FileSavePath == "0")
            {
                _view.RefreshDataCreateView();
                _view.RushViewData(_view.OrderViewList);
            }
            else
            {
                _view.FreezeFrm();
                //timeMove_Elapsed(null,null);
                bStopMove = false;
            }
            // LastList = _view.OrderViewList.Except(tempList).ToList();
            //_view.OrderViewList = LastList;
            // _view.RefreshDataCreateView();
            //    //_view.RushViewData(_view.OrderViewList);
            //}
            //else
            //{
            //    MessageBox.Show("当前还有"+CurrTask+"个目录未分析完成，请耐心等待","",MessageBoxButtons.OK,MessageBoxIcon.Warning);
            //    _view.ThawyFrm();

            //}

        }

        public void MoveDir()
        {

            int intRtn = _bll.MoveDirPhoto();
            if (intRtn != 0)
            {
                bStopMove = false;

            }
            else
            {
                bStopMove = true;
                _view.ThawyFrm();
            }

            if (_bll.GetUnMoveView().Count == 0)
            {
                _view.ThawyFrm();
            }
        }
        /// <summary>
        /// 选择目录导入
        /// </summary>
        public void CreateComplexView()
        {
            List<string> strlist = new List<string>();
            if (Directory.Exists(_view.CurrImportPath))
            {
                string[] paths = Directory.GetDirectories(_view.CurrImportPath);

                foreach (string s in paths)
                {
                    strlist.Add(s);
                }
            }
            CreateOrderView(strlist);
        }
        /// <summary>
        /// 获取错误的列表
        /// </summary>
        public void GetErrList()
        {
            _view.OrderErrorList = _bll.GetMoveErrorView();
            _view.DisPlayErrorList();
        }

        public int DelErrList(List<OrderViewDCT> inList)
        {
            return _bll.DelErrList(inList);
        }
        public static bool WrtieTextEn(StringBuilder sText, string sFile)
        {
            string directory = Path.GetDirectoryName(sFile);
            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }

            StreamWriter sw = new StreamWriter(sFile, true, Encoding.Default);
            try
            {
                string filePath = sFile;
                if (File.Exists(filePath))
                {
                    //sw = File.AppendAllText(sFile, sText.ToString(), Encoding.ASCII) ;

                    sw.WriteLine(sText);
                }
                else
                {
                    //sw = File.CreateText(sFile);
                    sw.WriteLine(sText);
                }
                //sw.Close();
                return true;
            }
            catch (Exception e)
            {
                string a = e.ToString();
                return false;
            }
            finally
            {
                sw.Close();
            }
        }

        internal bool CheckOrder(string orderName)
        {
            return _bll.CheckOrder(orderName);
        }

        internal void MoverFile()
        {
            //List<OrderInfo_PBDCT> moveList = _bll.GetMoveFileList();

            //foreach (OrderInfo_PBDCT order in moveList)
            //{


            //}
            _bll.MoveDirPhoto();
        }
    }
}
